<%@ page contentType="text/html;charset=UTF-8" %>
<%@ include file="/WEB-INF/views/mobile/include/taglib.jsp"%>
<html>
<head>
	<title>购物车</title>
	<%@include file="/WEB-INF/views/mobile/include/head.jsp" %>
	<link href="${ctxFront}/css/business.css" type="text/css" rel="stylesheet" />
	<style type="text/css">

	</style>
	<script type="text/javascript">
		var appId = '${appId}';
		var openNewUrl = "";
		var sid="${merchant.id}";
		var mobile="${mobile}";
		var classifyId = "${classifyId}";
		var shopModel = "${shopModel}";
		var products = new Array();
		var totalNumber = ${totalNumber};
		var totalAmount = ${totalAmount};
		var ctxFront = "${ctxFront}";
		var ctxShop = "${ctxShop}";
		var hasPrize = ${hasPrize};
		var gift = ${gift};//是否存在新用户礼包
		var $fee = ${fee};//派送费
		var $lowFee = ${lowFee};//起送费
		var userType = "${userType}";//用户类型，0新用户
		$(document).ready(function() {
			$("#listForm").validate({
				submitHandler: function(form){
					loading('正在提交，请稍等...');
					form.submit();
				},
				errorContainer: "#messageBox",
				errorPlacement: function(error, element) {
					$("#messageBox").text("输入有误，请先更正。");
					if (element.is(":checkbox")||element.is(":radio")||element.parent().is(".input-append")){
						error.appendTo(element.parent().parent());
					} else {
						error.insertAfter(element);
					}
				}
			});
			
			$("#listForm").bind("click", function(){
				if(!$(".more-menu").is(":hidden")){
					$(".more-menu").slideToggle(500);
				}
			});
			
			$(".poster").bind("click", function(){
				if(!$(".more-menu").is(":hidden")){
					$(".more-menu").slideToggle(500);
				}
				loading('正在跳转，请稍等...');
				setTimeout(function(){
					hideLoader();
					document.location="${ctxShop}/sysPoster?posterId=${merchant.activityPoster.id }&appId="+appId;				
				},1000);
			});
			
			$(".clause").bind("click", function(){
				if(!$(".more-menu").is(":hidden")){
					$(".more-menu").slideToggle(500);
				}
				loading('正在跳转，请稍等...');
				setTimeout(function(){
					hideLoader();
					document.location="${ctxShop}/sysClause?clauseId=${merchant.merchantClause.id }&appId="+appId;				
				},1000);
			});
			
			$(".phone").bind("click", function(){
				$(".more-menu").hide();
				$("#phonePopup").popup("open");
			});
			
			if(${fn:length(list)}>0){  //加载进来时封装商品信息
				products = new Array();
				<c:forEach items="${list}" var="cart" varStatus="ps">
					<c:set var="product" value="${cart.product}" scope="request"/>
					var item = new Object();
					item.id="${product.id}";
					item.price=${cart.price};
					item.startSaleNum=${product.startSaleNum}; //起购量
					item.purchaseNum=${product.purchaseNum};   //限购量
					item.cartId="${cart.id}";	 //购物车里对应该商品编号
					item.number=${cart.number};   //购物车里对应该商品购买数量
					item.amount=${cart.amount};   //购物车里对应该商品购买金额
					products.push(item);
					//调用判断商品是否可以操作
					checkShoppingCartAddOrDiffIcon(item);
				</c:forEach>
			}
			$(".totalAmount strong").text("￥"+changeTwoDecimal_f(totalAmount));
			//检测是否免运费
			checkFreeAmount();
		});
		function toSettlement(){
			//验证是否登录
			if(!checkLogin()) return;
			
			loading('正在提交，请稍等...');
			setTimeout(function(){
				hideLoader();
				document.location="${ctxShop}/order/toSettlement?sid="+sid+"&mobile="+mobile+"&classifyId="+classifyId+"&shopModel="+shopModel+"&appId="+appId+"&type=shoppingCart";				
			},1000);
		}
		function showProductDetail(url){
			loading('正在跳转，请稍等...');
			setTimeout(function(){
				hideLoader();
				document.location=url+"&sid="+sid+"&mobile="+mobile+"&classifyId="+classifyId+"&shopModel="+shopModel+"&appId="+appId;				
			},1000);
		}
	</script>
	<script type="text/javascript"> 
		$(document).ready(function() {
			//预加载图片
			startLoadImage();
		});
		function startLoadImage(){
			$(".displayImages").each(function(index){
				loadImage($(this).attr("id"),$(this).attr("path"),loadResult);
			});
		}
	</script>
	<script type="text/javascript"> 
		function iEventGetNavgitionInfo(){
			var result = {
				title:"购物车",
			    leftBtn:{ 
			    	type:2,	//0只显示返回,1只显示关闭，2显示返回，关闭
					backFun:""   //返回执行的事件，不带的话由iOS控制。
				},
				rightBtn:{
					bottons:[
						{
							type:1,			///0就是图片，1是文字,
							name:"清空",		//更多webNavMore.png 搜索webNavSearch.png
							fun:"iEventClearShoppingCart()"
						}
					]
				}               
			};
			if($global_isAndroid){
				window.control.onJsComplete(JSON.stringify(result));
				return;
			}
			return JSON.stringify(result);
		}
		/*function iEventGoBack(){
			if(${activity!=''})
				document.location=ctxShop+"/business/activity?id=${activity }&sid="+sid+"&mobile="+mobile+"&appId="+appId;
			else if(${detail!=''})
				document.location=ctxShop+"/product/detail?id=${detail }&sid="+sid+"&mobile="+mobile+"&classifyId="+classifyId+"&shopModel="+shopModel+"&appId="+appId;
			else
				document.location=ctxShop+"?sid="+sid+"&mobile="+mobile+"&classifyId="+classifyId+"&shopModel="+shopModel+"&appId="+appId;
		}*/
		function iEventShowMore(){
			showMoreMenu();
		}
		function iEventClearShoppingCart(){
			if($(".custom-list li").length==0){
				openPopup("当前购物车为空");
				closePopup(2000);
				return;
			}
			//$("#popupDialog").popup("open");
			document.location="ievent://showAlert?fun=iEventCleanCartAlert()";
		}
		function iEventCleanCartAlert(){
			var result = {
				title:"系统提示",
				message:"确定清空当前购物车？",
				buttons:[
					{
						title:"确定",
						fun:"cleanCart()" //函数名自定义的，根据json返回的fun节点值去调用相应的js函数
					},
					{
						title:"取消",
						fun:"" //同上，并且如果这里没给函数则直接执行提示层close关闭
					}	
				]		
				
			}
			if($global_isAndroid){
				window.control.showAlert(JSON.stringify(result));
				return;
			}
			return JSON.stringify(result);
		}
		function cleanCart(){
			clearShoppingCart('', 0);
		}
	</script>
	<script type="text/javascript">
		//定时器更新抢购活动时间
		setInterval("countdownTimer()",1000);//1000为1秒钟
		function countdownTimer(){
			$("input[name='updateDate']").each(function(i){
				var updateDate = $(this).val();
				var effectiveTime = parseInt($("input[id='effectiveTime']:eq("+i+")").val())*60*60*1000;
				var endDate = new Date(updateDate.replace(/\-/g, "\/"));
				var nowDate = new Date();
				var time=(endDate.getTime()-nowDate.getTime())+effectiveTime;//毫秒
				if(time<=0){
					var amount = changeTwoDecimal_f(parseInt($("input[id='number']:eq("+i+")").val())*parseFloat($("input[id='price']:eq("+i+")").val()));
					clearShoppingCart($("input[id='cartId']:eq("+i+")").val(), amount);
				}else
					reckonTime(i,time);
			});
		}
		function reckonTime(index,time){
			var hours=(time/(1000*60*60));
			hours = parseInt(hours);
			$(".hours:eq("+index+")").text(hours<10?0+""+hours:hours);
			time=time-hours*(1000*60*60);
			var minutes = time/(1000*60);
			minutes = parseInt(minutes);
			$(".minutes:eq("+index+")").text(minutes<10?0+""+minutes:minutes);
			time=time-minutes*(1000*60);
			var seconds = time/1000;
			seconds = parseInt(seconds);
			$(".seconds:eq("+index+")").text(seconds<10?0+""+seconds:seconds);
		}
		//减少商品
		function diffCart(productId, index){
			diffProductCart(productId, 1);
			//更新计时器
			var nowDate = new Date();
			var updateDate = nowDate.getFullYear()+"-"+(parseInt(nowDate.getMonth())+1)+"-"+nowDate.getDate()+" "+nowDate.getHours()+":"+nowDate.getMinutes()+":"+nowDate.getSeconds();
			$("input[id='updateDate']:eq("+index+")").val(updateDate);
		}
		//增加商品
		function addCart(productId, index, gift){
			if(gift=="1" && userType=="1"){//商品是新用户礼包并且用户是老用户，则不允许添加
				openPopup("仅限新用户领取！");
				closePopup(3000);
				return;
			}
			addProductCart(productId);
			//更新计时器
			var nowDate = new Date();
			var updateDate = nowDate.getFullYear()+"-"+(parseInt(nowDate.getMonth())+1)+"-"+nowDate.getDate()+" "+nowDate.getHours()+":"+nowDate.getMinutes()+":"+nowDate.getSeconds();
			$("input[id='updateDate']:eq("+index+")").val(updateDate);
		}
	</script>
</head>
<body data-role="page">
	<div role="main" class="ui-content" style="padding:0em 0em 3.25em 0em;">
		<div id="popup" data-role="popup" data-position-to="window" data-overlay-theme="a" data-theme="b" class="ui-content">
		  <p></p>
		</div>
		<div data-role="popup" id="popupDialog" data-overlay-theme="a" data-theme="a" data-dismissible="false" style="min-width: 300px;">
			<div data-role="header" data-theme="a">
		    	<h1>系统提示</h1>
		    </div>
		    <div role="main" class="ui-content">
		        <h3 class="ui-title" style="text-align: center;">确定清空当前购物车？</h3>
		        <a href="#" style="width: 30%; margin-left: 10px;" class="ui-btn ui-corner-all ui-shadow ui-btn-inline ui-btn-a" onclick="clearShoppingCart('', 0);" data-transition="flow">确定</a>
		        <a href="#" style="width: 30%;" class="ui-btn ui-corner-all ui-shadow ui-btn-inline ui-btn-a float-right" data-rel="back">取消</a>
		    </div>
		</div>
		<%@include file="/WEB-INF/views/mobile/layouts/checkLoginPopup.jsp" %>
		<form id="listForm" method="post" style="margin-bottom: 0em;">
		<input id="totalAmount" name="totalAmount" type="hidden" value="${totalAmount }" />
		<%@include file="/WEB-INF/views/mobile/layouts/shopCommon.jsp" %>
		<c:if test="${fn:length(list) != 0}">
		<div class="custom-module">
		<ul data-role="listview" class="custom-list">
		<c:forEach items="${list}" var="cart" varStatus="vs">
			<c:set var="product" value="${cart.product}" scope="request"/>
			<li id="${cart.id }" data-icon="false">
				<a id="${product.id }" data-transition="slide" href="#" style="background-color: #fff;">
				    <div class="product-img" onclick="showProductDetail('${ctxShop}/product/detail?id=${product.id }');">
				    	<img id="photo${vs.index }" class="displayImages" src="${ctxFront }/images/loading.png" path="${ctxShop}/download?filePath=${product.logoUrl }">
				    </div>
				    <h2>${product.name}</h2>
				    <c:if test="${fn:length(cart.actProductList)>0}"> <!-- 如果是抢购 -->
				    <p><label class="float-left price-color" style="font-size: 12px;">原价￥${product.price }</label></p>
					<p><label class="float-left amount"><strong>￥${cart.price }</strong></label></p>
				    <p class="ui-li-aside" style="bottom: 10px; top: auto; right: 16px;">
			        	<img class="float-right del" onclick="clearShoppingCart('${cart.id}', ${cart.number*cart.price })" alt="" src="${ctxFront }/images/shop/del-1.png"/>
			        </p>
				    <p class="ui-li-aside" style="top: 11px; left: 12px; right: auto;">
			        	<img src="${ctxFront }/images/shop/icon_9.png" width="35"/>
			        </p>
			        <p style="top: 7px; position: absolute; right: 20px;"><label class="price-color">距离失效</label></p>
				    <p style="top: 27px; position: absolute; right: 8px;">
				    	<input type="hidden" id="cartId" name="cartId" value="${cart.id }"/>
				    	<input type="hidden" id="number" name="number" value="${cart.number }"/>
				    	<input type="hidden" id="price" name="price" value="${cart.price }"/>
				    	<input type="hidden" id="updateDate" name="updateDate" value="<fmt:formatDate value="${cart.updateDate }" pattern="yyyy-MM-dd HH:mm:ss"/>"/>
				    	<input type="hidden" id="effectiveTime" name="effectiveTime" value="1"/>
				    	<label class="float-left color-huise min-time hours" style="font-size: 14px;">00</label>
				    	<label class="float-left" style="font-size: 14px;">:</label>
				    	<label class="float-left color-huise min-time minutes" style="font-size: 14px;">00</label>
				    	<label class="float-left" style="font-size: 14px;">:</label>
				    	<label class="float-left color-huise min-time seconds" style="font-size: 14px;">00</label>
				    </p>
				    </c:if>
				    <c:if test="${fn:length(cart.actProductList)==0}"> <!-- 如果不是抢购 -->
				    <p><label class="float-left price-color">单价：</label><label class="float-left amount"><strong>￥${cart.price }</strong></label>
				    </p>
				    <p style="top: 7px; position: absolute; right: 20px;"><label class="price-color">距离失效</label></p>
				    <p style="top: 27px; position: absolute; right: 8px;">
				    	<input type="hidden" id="cartId" name="cartId" value="${cart.id }"/>
				    	<input type="hidden" id="number" name="number" value="${cart.number }"/>
				    	<input type="hidden" id="price" name="price" value="${cart.price }"/>
				    	<input type="hidden" id="updateDate" name="updateDate" value="<fmt:formatDate value="${cart.updateDate }" pattern="yyyy-MM-dd HH:mm:ss"/>"/>
				    	<input type="hidden" id="effectiveTime" name="effectiveTime" value="${cart.product.effectiveTime }"/>
				    	<label class="float-left color-huise min-time hours" style="font-size: 14px;">00</label>
				    	<label class="float-left" style="font-size: 14px;">:</label>
				    	<label class="float-left color-huise min-time minutes" style="font-size: 14px;">00</label>
				    	<label class="float-left" style="font-size: 14px;">:</label>
				    	<label class="float-left color-huise min-time seconds" style="font-size: 14px;">00</label>
				    </p>
			        <p>
			        	<img class="float-left diff" status="0" onclick="diffCart('${product.id}', ${vs.index })" alt="" src="${ctxFront }/images/shop/diff-1.png">
			        	<label class="float-left choice-num"><strong>${cart.number }</strong></label>
			        	<img class="float-left add" status="1" onclick="addCart('${product.id}', ${vs.index }, ${product.gift })" alt="" src="${ctxFront }/images/shop/add-2.png"/>
			        	<img class="float-right del" onclick="clearShoppingCart('${cart.id}', ${cart.number*cart.price })" alt="" src="${ctxFront }/images/shop/del-1.png"/>
			        </p>
				    </c:if>
			    </a>
		    </li>
		</c:forEach>
		</ul>
		</div>
		</c:if>
		<div class="cart-empty" style="${fn:length(list) > 0?'display:none;':''}">
			<img alt="" src="${ctxFront }/images/shop/gwc_0.png" width="50" height="50" style="vertical-align: middle;">&nbsp;您的购物车还没有商品！
			<!-- button onclick="homePage()" type="button" data-iconshadow="true" class="btn btn-primary back-homepage">返回首页选购商品</button -->
		</div>
		</form>
	</div>
	<div data-role="footer" class="ui-footer" data-position="fixed" data-tap-toggle="false"
		style="${fn:length(list) == 0?'display:none;':''}">
		<div class="float-left footer-left">
			<div class="a">
				<label class="float-left" style="width: 35%; text-align: left;">总金额：</label>
				<label class="float-right amount totalAmount" style="width: 65%; text-align: right; margin-top: -10px;"><strong>￥${totalAmount }</strong></label>
				<label class="float-right freeDiffAmount" style="width: 65%; text-align: right; font-size: 12px;">(还差<strong></strong>元免运费)</label>
			</div>
	    </div>
		<div class="float-right footer-right">
			<img class="float-right" alt="" src="${ctxFront }/images/shop/gwc_2.png" height="35" style="margin: 7.5px 1em 7.5px 0px;" onclick="toSettlement()">
			<!-- <img class="float-right" alt="" src="${ctxFront }/images/shop/gwc_1.png" height="35" style="margin: 7.5px 1em 7.5px 0px;" onclick="clearShoppingCart('', 0)"> -->
	    </div>
	</div><!-- /footer -->
</body>
</html>
